import 'dart:convert';
import 'dart:developer';
import 'dart:io';
import 'package:flutter/services.dart';

import 'package:emphasize_word/save.dart';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'package:provider/provider.dart';

var awaitTimer = 0;

///群组
class Group with ChangeNotifier {
  getGroup(context) async {
    var data = await DefaultAssetBundle.of(context).loadString('lib/data.json');
    var tmp = json.decode(data);
    var tmp_res = [];
    for (var i = 1; i <= 10; i++) {
      tmp_res.add(tmp["Group"]["list${i}"]);
    }
    return tmp_res;
  }
}

///难度
class Similar with ChangeNotifier {
  getData(context, File file) async {
    var data = await file.readAsString();
    var tmp = json.decode(data);
    var tmpRes = [];
    for (var i = 1; i <= 10; i++) {
      tmpRes.add(tmp["list$i"]);
    }
    // Clipboard.setData(ClipboardData(text: "HHH"));
    return tmpRes;
  }

  setSimilar(int list, int index, int similar) async {
    if (awaitTimer == 1) return;
    awaitTimer = 1;
    Directory tempDir = await getTemporaryDirectory();
    final file = File('${tempDir.path}/similar.json');
    var data = await file.readAsString();
    var tmp = json.decode(data);
    tmp["list$list"][index] = similar;
    file.writeAsString(jsonEncode(tmp));
    awaitTimer = 0;
    return;
  }

  getSimilar(context) async {
    if (awaitTimer == 1) return;
    // ignore: unnecessary_statements
    awaitTimer == 1;
    Directory tempDir = await getTemporaryDirectory();
    String tempPath = tempDir.path;
    final file = File('$tempPath/similar.json');
    var exists = await file.exists();
    if (!exists) {
      //创建新的
      await file.create();
      var data =
          await DefaultAssetBundle.of(context).loadString('lib/data.json');
      var tmp = json.decode(data);
      file.writeAsString(jsonEncode(tmp["Similar"]));
    }
    awaitTimer = 0;
    return await getData(context, file);
  }
}

///计划表
class Schedule with ChangeNotifier {
  var day1 = [1, 2];
  var day2 = [3, 4, 1, 2];
  var day3 = [5, 6, 1, 3, 2, 4];
  var day4 = [7, 8, 1, 2, 3, 4, 5, 6];
  var day5 = [9, 10, 3, 4, 5, 6, 7, 8];
  var day6 = [1, 2, 5, 6, 9, 10];
  var day7 = [3, 4, 7, 8, 9, 10];
  var day8 = [5, 6, 7, 8, 9, 10];
  var day9 = [1, 2, 3, 4, 9, 10];
  var day10 = [5, 6, 7, 8, 9, 10];
  List<List> getSchedule() {
    return [day1, day2, day3, day4, day5, day6, day7, day8, day9, day10];
  }
}

class Done with ChangeNotifier {
  setDone(context) async {
    await getDone(context);
    ListSave provider = Provider.of<ListSave>(context, listen: false);
    Directory tempDir = await getTemporaryDirectory();
    String tempPath = tempDir.path;
    final file = File('$tempPath/done.json');
    var file_tmp = await file.readAsString();
    var file_tmp_tmp = json.decode(file_tmp);
    print(file_tmp_tmp);
    file_tmp_tmp["day${provider.total_day_index + 1}"].add(provider.now_number);
    await file.writeAsString(json.encode(file_tmp_tmp));
  }

  getDone(context) async {
    Directory tempDir = await getTemporaryDirectory();
    String tempPath = tempDir.path;
    final file = File('$tempPath/done.json');
    print("$tempPath/done.json");
    var exists = await file.exists();
    if (!exists) {
      //创建新的
      await file.create();
      file.writeAsString(jsonEncode({
        "day1": [],
        "day2": [],
        "day3": [],
        "day4": [],
        "day5": [],
        "day6": [],
        "day7": [],
        "day8": [],
        "day9": [],
        "day10": []
      }));
    }
    var data = await file.readAsString();
    var datatmp = json.decode(data);
    List tmp = [];
    for (var i = 1; i <= 10; i++) {
      tmp.add(datatmp["day$i"]);
    }
    return tmp;
  }
}

class DisplayEnglish with ChangeNotifier {
  int display = 0;
  switchDis(int index) {
    display = index;
    notifyListeners();
  }
}

class ListSave with ChangeNotifier {
  ScrollController listViewController = new ScrollController();
  var similars = []; //当前所有单词的难度
  var datalists = []; //当前所有单词
  var now_number = 4; //现在的词组编号，显示的编号 var number = 4;
  var total_index = []; //当天的所有词组 var day4 = [3, 4, 5];
  var total_day_index = 0; //当天
  var sort = 0; //0-初始排序 1-难度排序
  var done_flag = 0; //0-请打卡 1-已打卡 2-不能打卡

  var sorted1_similars = [];
  var sorted1_datalists = [];

  ListSave() {}

  changeSort(int s) {
    sortAgain();
    sort = s;
    listViewController.animateTo(
      .0,
      duration: Duration(milliseconds: 300),
      curve: Curves.bounceInOut,
    );
    notifyListeners();
  }

  sortAgain() {
    List datalistsTmp = datalists;
    List similarsTmp = similars;
    List<Map<String, dynamic>> datalistsAndSimilar = [];
    for (var i = 0; i < datalistsTmp.length; i++) {
      datalistsAndSimilar.add({
        "data": datalistsTmp[i],
        "similar": similarsTmp[i],
      });
    }
    datalistsAndSimilar.sort((a, b) {
      return (b["similar"].compareTo(a["similar"]));
    });
    List datalistsResTmp = [];
    List similarsResTmp = [];
    datalistsAndSimilar.forEach((element) {
      datalistsResTmp.add(element["data"]);
      similarsResTmp.add(element["similar"]);
    });
    sorted1_datalists = datalistsResTmp;
    sorted1_similars = similarsResTmp;
    notifyListeners();
  }

  minusSimilar(int index, context) {
    Similar provider = Provider.of<Similar>(context, listen: false);
    if (sort == 0) {
      similars[index]--;
      sortAgain();
      provider.setSimilar(now_number, index, similars[index]);
    } else {
      sorted1_similars[index]--;
      similars[datalists.indexOf(sorted1_datalists[index])]--;
      provider.setSimilar(
        now_number,
        datalists.indexOf(sorted1_datalists[index]),
        sorted1_similars[index],
      );
    }
    notifyListeners();
  }

  addSimilar(int index, context) {
    Similar provider = Provider.of<Similar>(context, listen: false);
    if (sort == 0) {
      similars[index]++;
      sortAgain();
      provider.setSimilar(now_number, index, similars[index]);
    } else {
      sorted1_similars[index]++;
      similars[datalists.indexOf(sorted1_datalists[index])]++;
      provider.setSimilar(
        now_number,
        datalists.indexOf(sorted1_datalists[index]),
        sorted1_similars[index],
      );
    }
    notifyListeners();
  }

  setNumber(int i) {
    now_number = i;
    notifyListeners();
  }

  //切换天数
  changeTotalIndex(int index, BuildContext context) {
    listViewController.animateTo(
      .0,
      duration: Duration(milliseconds: 300),
      curve: Curves.bounceInOut,
    );
    List schedule = Schedule().getSchedule();
    total_index = schedule[index];
    total_day_index = index;
    now_number = schedule[index][0];
    // getDoneFlag(context);
    getData(context, now_number);
  }

  getIndex(context) async {
    List schedule = Schedule().getSchedule();
    List done = await Done().getDone(context);
    for (var i = 0; i < schedule.length; i++) {
      if (schedule[i].length != done[i].length) {
        now_number = schedule[i][done[i].length];
        total_day_index = i;
        total_index = schedule[i];
        break;
      }
    }
    notifyListeners();
  }

  ///用编号索引出List
  getList(int now_number, context) async {
    List tmp = [];
    var tmp_arr = json.decode(
      await DefaultAssetBundle.of(context).loadString('lib/list.json'),
    );
    var no_arr = await Group().getGroup(context);
    no_arr[now_number].forEach((element) {
      tmp.add(tmp_arr[element]);
    });
    return tmp;
  }

  indexof(List arr, int ele) {
    for (var i = 0; i < arr.length; i++) {
      if (arr[i] == ele) {
        return i;
      }
    }
    return -1;
  }

  getDoneFlag(context) async {
    var schedule = Schedule().getSchedule();
    var done = await Done().getDone(context);
    var now_shedule = schedule[total_day_index];
    var now_done = done[total_day_index];
    // print("$now_shedule");
    // print("$now_done");
    // print("$total_day_index");
    // print("$now_number");
    // print("${now_shedule.indexOf(now_number)}");
    if (now_shedule.length == now_done.length) {
      done_flag = 1;
    }
    if (now_done.length < now_shedule.length) {
      if (indexof(now_shedule, now_number) == now_done.length) {
        if (total_day_index >= 1 &&
            schedule[total_day_index - 1].length ==
                done[total_day_index - 1].length) {
          done_flag = 0;
        } else if (total_day_index == 0) {
          done_flag = 0;
        }
      } else if (indexof(now_shedule, now_number) < now_done.length) {
        done_flag = 1;
      } else {
        done_flag = 2;
      }
    }
    print("done_flag:$done_flag");
    notifyListeners();
  }

  getData(context, index) async {
    if (datalists.length != 0 && index == -1) {
      return datalists;
    }
    if (total_index.length == 0) {
      await getIndex(context);
    }
    int request_number = index == -1 ? now_number : index;
    datalists = await getList(request_number - 1, context);
    var similars_tmp = await Similar().getSimilar(context);
    similars = similars_tmp[request_number - 1]; //从零开始索引
    // print("请求编号:${request_number}");
    // print("当前列表:${total_index}");
    sortAgain();
    await getDoneFlag(context);
    notifyListeners();
    return datalists;
  }
}
